package village.rainbow.dailyscene.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import village.rainbow.dailyscene.BaseActivity;
import village.rainbow.dailyscene.Global;
import village.rainbow.dailyscene.R;
import village.rainbow.dailyscene.adapter.ViewPagerAdapter;
import village.rainbow.dailyscene.datamodel.DataRow;
import village.rainbow.dailyscene.datamodel.DataRowBean;
import village.rainbow.dailyscene.datamodel.DataTable;
import village.rainbow.dailyscene.exception.ToFinishException;
import village.rainbow.dailyscene.uicontrol.RoundButton;
import village.rainbow.dailyscene.util.AnimatedGifEncoder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewActivity extends BaseActivity {

	private DataRow mData = new DataRow();
	private ViewPager mPager;
	private ViewPagerAdapter mPagerAdapter;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_view);
		 
		TextView tvTitle = (TextView)findViewById(R.id.menu_title);
		tvTitle.setText("View Scene");
		Log.i("VILLAGE", getIntent().toString());
		
		Bundle b = getIntent().getExtras();
		
		try{
			String sceneId = "";
			// 숏컷을 통해 들어온 경우
			if(getIntent().getDataString() != null && getIntent().getDataString().startsWith("content:")){
				String contentData = getIntent().getDataString();
				List<String> list = Arrays.asList(contentData.split("/"));
				sceneId = list.get(list.size() - 1); // 마지막이 SCENE_ID
			}
			// 아닌 경우
			else{
				//중에서 리스트를 클릭해서 들어왔을 때
				if(b != null && b.containsKey("DATA")){
					DataRowBean bean = (DataRowBean) b.getSerializable("DATA");
					DataRow row = bean.getDataRow();
					sceneId = row.getString("SCENE_ID", "");
				}
				// 알람을 통해서 들어왔을 때
				else if(b != null && b.containsKey("SCENE_ID")){
					sceneId = b.getString("SCENE_ID", "");
				}
				
			}
			
			mData = mDao.getScene(sceneId);
			if(mData.isEmpty())
				throw new ToFinishException("데이터 없네");
			
		}catch(Exception e){
			errorHandler(e);
		}
		
		
		DataTable table = (DataTable) mData.get("SCENE_DETAIL", new DataTable());
		mPagerAdapter = new ViewPagerAdapter(this, new DataTable(), false);
		
		mPager = (ViewPager)findViewById(R.id.pager);
		mPager.setAdapter(mPagerAdapter);
		mPagerAdapter.setOnClickListener(this);
		mPager.setCurrentItem(mPagerAdapter.getCount()-1, false);
		mPagerAdapter.addAll(table);
		mPagerAdapter.notifyDataSetChanged();
		
		RoundButton btnShare  = (RoundButton)findViewById(R.id.btn_map);
		RoundButton btnDelete = (RoundButton)findViewById(R.id.btn_delete);
		RoundButton btnEdit   = (RoundButton)findViewById(R.id.btn_edit);
		btnShare.setOnClickListener(this);
		btnDelete.setOnClickListener(this);
		btnEdit.setOnClickListener(this);
		
	};	
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		
		int id = v.getId();
		switch(id){
			case R.id.btn_map:
				viewOnMap();
				break;
			case R.id.btn_delete:
				deleteThis();
				break;
			case R.id.btn_edit:
				Intent i = new Intent(ViewActivity.this, SceneActivity.class);
				i.putExtra("DATA", new DataRowBean(mData));
				startActivityForResult(i, 1002);
				break;
		}
		
	}
	
	private void viewOnMap(){
		
		int position = mPager.getCurrentItem();
		String imgLocation = mPagerAdapter.getItems().get(position).getString("SCENE_PIC_LOCATION", "");
		
		try {
			ExifInterface exifInterface = new ExifInterface(imgLocation);
			String latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
			String latitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
			String lati = calcLati(latitude, latitudeRef);
			
			String longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
			String longitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
			String longi = calcLongi(longitude, longitudeRef);
			
			if(!lati.equals("null") && !longi.equals("null")){
				String uri = "geo:" + lati + ","+ longi;
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
				Toast.makeText(ViewActivity.this, "finished",Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(ViewActivity.this, "Can not find location information",Toast.LENGTH_SHORT).show();
			}
		} catch (IOException e) {
			errorHandler(e);
		}
		
	}
	
	private String calcLati(String latitude, String gpsLatitudeRef) {
		if(latitude == null || gpsLatitudeRef == null)
			return "null";
		if(latitude.toUpperCase().equals("NULL"))
			return "null";
		if(latitude.indexOf(",") == -1)
			return "null";
		
		String[] lati = latitude.split(",");
		
		String[] lati0 = lati[0].split("/");
		String[] lati1 = lati[1].split("/");
		String[] lati2 = lati[2].split("/");
		
		double l01 = Double.parseDouble(lati0[0]);
		double l02 = Double.parseDouble(lati0[1]);
		double l0 = l01/l02;
		
		double l11 = Double.parseDouble(lati1[0]);
		double l12 = Double.parseDouble(lati1[1]);
		double l1 = l11/(l12*60);
		
		double l21 = Double.parseDouble(lati2[0]);
		double l22 = Double.parseDouble(lati2[1]);
		double l2 = l21/(l22*3600);
		
		double fin = l0 + l1 + l2;
		
		if(!gpsLatitudeRef.equals("N"))
			fin *= -1;
		return fin + "";
	}
	
	private String calcLongi(String latitude, String gpsLatitudeRef) {
		if(latitude == null || gpsLatitudeRef == null)
			return "null";
		if(latitude.toUpperCase().equals("NULL"))
			return "null";
		if(latitude.indexOf(",") == -1)
			return "null";
		
		String[] lati = latitude.split(",");
		
		String[] lati0 = lati[0].split("/");
		String[] lati1 = lati[1].split("/");
		String[] lati2 = lati[2].split("/");
		
		double l01 = Double.parseDouble(lati0[0]);
		double l02 = Double.parseDouble(lati0[1]);
		double l0 = l01/l02;
		
		double l11 = Double.parseDouble(lati1[0]);
		double l12 = Double.parseDouble(lati1[1]);
		double l1 = l11/(l12*60);
		
		double l21 = Double.parseDouble(lati2[0]);
		double l22 = Double.parseDouble(lati2[1]);
		double l2 = l21/(l22*3600);
		
		double fin = l0 + l1 + l2;
		
		if(!gpsLatitudeRef.equals("E"))
			fin *= -1;
		return fin + "";
	}
	
	private void deleteThis() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("알림");
		builder.setMessage("Scene을 삭제 하시겠습니까?");
		builder.setPositiveButton("삭제", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try{
					String sceneInsDt = mData.getString("SCENE_ID", "");
					mDao.deleteScene(sceneInsDt);	
					ViewActivity.this.finish();
				}catch(Exception e){
					errorHandler(e);
				}
			}
		} );
		builder.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == Activity.RESULT_OK)
			this.finish();
	}
	
	
	
	private boolean mPreventDoubleClick = false;
	
	private void showShareDialog(final Bitmap firstBitmap, final String firstText, final DataTable sceneDetailList) {

		if(mPreventDoubleClick)
			return;

		mPreventDoubleClick = true;

		try{
			String[] items = {"현재 사진 내보내기", "GIF로 전부 내보내기", "텍스트를 입력하여 GIF로 보내기", "닫기"};
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("사진 선택");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch(which){
					case 0:
						try {
							shareScene(firstBitmap, firstText);
						} catch (Exception e) {
							e.printStackTrace();
						}
						break;
					case 1:
						shareViaGif(sceneDetailList);
						break;
					case 2:
						shareViaGif(sceneDetailList, true);
						break;
					case 3:
						break;
					}
					dialog.dismiss();
				}
			});
			AlertDialog dialog = builder.create();
			dialog.show();	

			mPreventDoubleClick = false;

		}catch(Exception e){
			errorHandler(e);
		}

	}
	
	protected void shareViaGif(DataTable sceneDetailList){
		shareViaGif(sceneDetailList, false);
	}

	protected void shareViaGif(DataTable sceneDetailList, boolean b) {

		AnimatedGifEncoder encoder = new AnimatedGifEncoder();

		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = sdf.format(new Date());

			File dir = new File(Environment.getExternalStorageDirectory().getPath() + Global.SDCARD_PATH + "/gif");
			if(!dir.exists())
				dir.mkdir();
			File outputFile = new File(dir, fileName + ".gif");
			if(outputFile.exists())
				outputFile.delete();
			outputFile.createNewFile();

			FileOutputStream fous = new FileOutputStream(outputFile);
			encoder.setDelay(750);
			encoder.start(fous);

			for(DataRow row : sceneDetailList){
				String picturePath = row.getString("SCENE_PIC_LOCATION", "");
				if(picturePath.equals(""))
					continue;				
				String text = row.getString("SCENE_TEXT", "");

				Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
				if(!text.equals("")){
					bitmap = writingText(bitmap, text);
				}
				encoder.addFrame(bitmap);
			}

			encoder.finish();
			fous.close();

			String gifImgFilePath = outputFile.getAbsolutePath();
			shareSceneGif(gifImgFilePath);

		}catch(Exception e){
			e.printStackTrace();
		}

	}
}
